package com.rehome.udp;


import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UDPClient implements ActionListener, Runnable {
    private DatagramSocket datagramSocket;
    private Thread thread = null;
    private UDPFrame clientFrame;

    public UDPClient() {
        JPanel panel = new JPanel();

        clientFrame = new UDPFrame("UDPClient");
        clientFrame.add(panel);

        clientFrame.placeComponents(panel);
        clientFrame.setVisible(true);

        clientFrame.getConnect().addActionListener(e -> {
            try {
                //host:"127.0.0.1"
                //String host = UDPClientFrame.getIpField().getText();
                //port:8887
                int dSocketPort = Integer.parseInt(clientFrame.getDSocketField().getText());
                datagramSocket = new DatagramSocket(dSocketPort);
                clientFrame.getTextArea().append("[连接] : 正在连接中……\n");
                clientFrame.getTextArea().append("\t连接成功\n");

                thread = new Thread(this);
                thread.setPriority(Thread.MIN_PRIORITY);
                thread.start();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        });

        clientFrame.getTransmit().addActionListener(this);
        clientFrame.getTextArea().append("……UDP客户端启动……\n");
        System.out.println("……UDP客户端启动……\n");

    }

    public static void main(String[] args) {
        new UDPClient();
    }

    //向服务器端发送数据
    @Override
    public void actionPerformed(ActionEvent e) {
        //String send = UDPClientFrame.getSendField().getText();
        //port:8888
        //发送消息
        new UDPSend(datagramSocket, clientFrame, "客户端").sendMessages();
    }

    //使用线程处理客户端接收服务器端的数据
    @Override
    public void run() {
        byte[] bytes = new byte[1024];
        DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length);
        new UDPReceive(datagramSocket, datagramPacket, clientFrame, "服务器端").receiveMessages();
    }
}
